package counter.console;

import java.io.InputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Console {
    private Map<String, ConsoleCommand> commands = new HashMap<String, ConsoleCommand>();

    private static PrintStream out = System.out;
    private static InputStream in = System.in;

    public Console() {
        commands.put("calc", new CalculateSummaryInfoCommand());
        commands.put("print", new ConsolePrintCommand());
        commands.put("quit", new QuitCommand());
    }

    public static void main(String... args) {
        new Console().start();
    }

    private void start() {
        Scanner scanner = new Scanner(in);
        System.out.println("type \"help\" for help =)" );
        while (true) {
            String commandString = scanner.nextLine();
            if (!commandString.trim().isEmpty()) {
                try {
                    execute(commandString);
                } catch (Exception ex) {
                    out.println("Error! " + ex);
                }
            }
        }
    }

    private void execute(String command) {
         String[] commandParts = command.trim().split("\\s+");
         if (commandParts.length > 0) {
             String commandName = commandParts[0];
             ConsoleCommand consoleCommand = commands.get(commandName);
             if (consoleCommand != null) {
                 String[] params = null;
                 if (commandParts.length > 1) {
                     params = Arrays.copyOfRange(commandParts, 1, commandParts.length);
                 }
                 System.out.println("Starting \"" + commandName + "\" command");
                 consoleCommand.execute(params);
                 System.out.println("Command \"" + commandName + "\" ended");
             } else {
                 throw new UnsupportedOperationException("Unknown command: " + commandName);
             }
         }
    }
}
